package com.leetcode.根据数据结构分类.链表;

import com.leetcode.datastructure.ListNode;

/**
 * @author: xiaomi
 * @date: 2021/3/27
 * @description: 61. 旋转链表
 * https://leetcode-cn.com/problems/rotate-list/
 */
public class B_61_旋转链表 {

    public static void main(String[] args) {

    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        ListNode guard = new ListNode(0);
        guard.next = head;
        ListNode curNode = head;
        ListNode tailNode = null;
        int size = 0;
        while (curNode != null) {
            tailNode = curNode;
            curNode = curNode.next;
            size++;
        }
        //1.先计算链表的长度，获取真正需要处理的步数
        int step = k % size;
        if (step == 0) {
            //如果步长 == 0
            return head;
        }
        int n = size - step;
        curNode = head;
        ListNode prevNode = guard;
        while (n > 0) {
            prevNode = curNode;
            curNode = curNode.next;
            n--;
        }
        tailNode.next = head;
        guard.next = curNode;
        prevNode.next = null;
        return guard.next;

    }
}
